package com.century.sjt.activity.wallet;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.activity.Pay.MerchantActivity;
import com.century.sjt.activity.Pay.MerchatTransactionActivity;
import com.century.sjt.activity.Pay.TransactionActivity;
import com.century.sjt.adapter.GridViewAdapter;
import com.century.sjt.entity.MgridView;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author:周玲波
 * @Description: 钱包
 * @date : 2016/8/17 11:08
 */
public class WalletActivity extends BaseActivity {
    @BindView(R.id.wallet_gv)
    GridView wallet_gv;
    @BindView(R.id.jump_small_tv)
    TextView jump_small_tv;
    @BindView(R.id.eye_tv)
    TextView eye_tv;
    @BindView(R.id.wallet_title)
    SjtTitleBar wallet_title;
    @BindView(R.id.layout_wallet_balance)
    LinearLayout layoutBalance;
    @BindView(R.id.wallet_balance)
    LinearLayout wallet_balance;
    @BindView(R.id.tv_wallet_account_balance)
    TextView tvBalance;
    @BindView(R.id.wallet_gvitem_icon)
    TextView wallet_gvitem_icon;
    @BindView(R.id.ll_open_translate)
    LinearLayout ll_open_translate;
    @BindView(R.id.tv_currencyCode)
    TextView tv_currencyCode;
    private String isShop, isMerchant;
    private String Bamount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sjt_wallet_activity);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取余额信息
        queryBalance();
    }

    @Override
    protected void initView() {
        wallet_title.setTitle(getResources().getString(R.string.s_purse));
        wallet_title.setLeftIconResource(getResources().getString(R.string.icon_return));
        wallet_title.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        isShop = mainSharedPreferences.getString("isShop", "");
        isMerchant = mainSharedPreferences.getString("isMerchant", "");


        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        jump_small_tv.setTypeface(iconfont);
        eye_tv.setTypeface(iconfont);
        wallet_gvitem_icon.setTypeface(iconfont);
        wallet_gv.setAdapter(new GridViewAdapter(initGridView(), this, iconfont));

        if (isMerchant.equals("0") & isShop.equals("0")) {
            //用户
            wallet_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (position) {
                        case 0:
                            //银行卡
                            if ("1".equals(isShop) && "0".equals(isMerchant)) {
                            } else {
                                startActivity(WalletActivity.this, BankCardActivity.class);
                            }
                            break;
                        case 1:
                            //商家支付
                            if ("1".equals(isShop) || "1".equals(isMerchant)) {
//                                TipUtil.showToast("商家暂未开放支付权限，敬请期待！", mContext, 1);
                                TipUtil.showToast(getResources().getString(R.string.error_isshop_isno_pay), WalletActivity.this, 1);
                            } else {
                                Intent intent2 = new Intent();
                                intent2.setClass(WalletActivity.this, MerchantActivity.class);
                                intent2.putExtra("payType", "2");
                                startActivity(intent2);
                            }
                            break;
                        case 2:
                            if (isShop.equals("1") || isMerchant.equals("1")) {
                                //商家交易记录
                                startActivity(WalletActivity.this, MerchatTransactionActivity.class);
                            } else {
                                //普通用户交易记录
                                startActivity(WalletActivity.this, TransactionActivity.class);
                            }
                            break;
                        case 3:
//                        翻译
                            if (isShop.equals("1") || isMerchant.equals("1")) {
                                //商家交易记录(分店不可进入)
                                startActivity(WalletActivity.this, TranslateShopActivity.class);
                            } else {
                                //普通用户交易记录
                                startActivity(WalletActivity.this, TranslateActivity.class);
                            }
//                        startActivity(WalletActivity.this,TranslateShopActivity.class);
                            break;
                    }
                }
            });
        } else {
            //商家
            wallet_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (position) {
                       //交易记录
                        case 0:
                            if (isShop.equals("1") || isMerchant.equals("1")) {
                                //商家交易记录
                                startActivity(WalletActivity.this, MerchatTransactionActivity.class);
                            } else {
                                //普通用户交易记录
                                startActivity(WalletActivity.this, TransactionActivity.class);
                            }
                            break;
                        //银行卡
                        case 1:
                            if ("1".equals(isShop) && "0".equals(isMerchant)) {
                            } else {
                                startActivity(WalletActivity.this, BankCardActivity.class);
                            }
                            break;
                    }
                }
            });
        }


    }

    @Override
    protected void initEvent() {
        layoutBalance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("1".equals(isShop) && "0".equals(isMerchant)) {
//                    TipUtil.showToast("您未获得该权限！", mContext, 1);
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("Bamount", Bamount);
                    intent.setClass(WalletActivity.this, WalletBalanceActivity.class);
                    startActivity(intent);
                }

            }
        });
        wallet_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(isShop) && "0".equals(isMerchant)) {
//                    TipUtil.showToast("您未获得该权限！", mContext, 1);
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("Bamount", Bamount);
                    intent.setClass(WalletActivity.this, WalletBalanceActivity.class);
                    startActivity(intent);
                }
            }
        });

        //开通翻译服务
        ll_open_translate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShop.equals("1") || isMerchant.equals("1")) {
                    //商家交易记录(分店不可进入)
                    startActivity(WalletActivity.this, TranslateShopActivity.class);
                } else {
                    //普通用户交易记录
                    startActivity(WalletActivity.this, TranslateActivity.class);
                }
            }
        });

    }

    @Override
    protected void initData() {

    }

    /**
     * @Description: 初始化GridView数据
     * @author: 周玲波
     * @date: 2016/8/17 11:33
     */
    private List<MgridView> initGridView() {
        List<MgridView> gvList = new ArrayList<>();

        //判断是商家、分店还是用户
        if (isMerchant.equals("0") & isShop.equals("0")) {
            ll_open_translate.setVisibility(View.GONE);
            gvList.clear();
            String name =getResources().getString( R.string.text_bankcard)+","+getResources().getString(R.string.tab_merchant) +","+getResources().getString( R.string.text_t_pay)+","+getResources().getString( R.string.text_open_translation);
            String icon[] = {getResources().getString(R.string.icon_card), getResources().getString(R.string.icon_store),
                    getResources().getString(R.string.icon_transaction), getResources().getString(R.string.icon_translation)};
            for (int i = 0; i < icon.length; i++) {
                MgridView mv = new MgridView();
                mv.setIcon(icon[i]);
                mv.setName(name.split(",")[i]);
                gvList.add(mv);
            }

        } else {
            ll_open_translate.setVisibility(View.VISIBLE);
            gvList.clear();
            String name =getResources().getString(R.string.text_t_pay)+","+getResources().getString(R.string.text_bankcard);
            String icon[] = {getResources().getString(R.string.icon_transaction), getResources().getString(R.string.icon_card)};
            for (int i = 0; i < icon.length; i++) {
                MgridView mv = new MgridView();
                mv.setIcon(icon[i]);
                mv.setName(name.split(",")[i]);
                gvList.add(mv);
            }
        }

        return gvList;
    }

    /**
     * 获取余额
     */

    private void queryBalance() {
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), WalletActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.QueryBalanceHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取用户余额成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("407")) {//异地登陆
                        TipUtil.showAppayRes(WalletActivity.this);
                    } else if (code.equals("200")) {//成功
                        JSONObject data = res.getJSONObject("data");
                        String amount = data.getString("amount");
                        String currencyCode = data.getString("currencyCode");
                        String currency = data.getString("currency");
                        tvBalance.setText(amount);
                        tv_currencyCode.setText("("+currencyCode+")");
                    } else {//失败
                        TipUtil.showToast(message, WalletActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), WalletActivity.this, 1);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), WalletActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

}
